import os
import re
from datetime import datetime, timedelta
import tkinter as tk
from tkinter import filedialog
import pandas as pd

def select_input_file_path():
    root = tk.Tk()
    root.withdraw()
    return filedialog.askopenfilename(
        defaultextension="选择任意一个文件",
        filetypes=[("Log files", "*.log"), ("All files", "*.*")]
    )

def select_output_file_path():
    root = tk.Tk()
    root.withdraw()
    return filedialog.asksaveasfilename(
        defaultextension=".xlsx",
        filetypes=[("Excel files", "*.xlsx"), ("All files", "*.*")]
    )

def generate_time_intervals(start, end, interval):
    intervals = []
    current = start
    while current < end:
        next_time = current + timedelta(minutes=interval)
        intervals.append((current, min(next_time, end)))
        current = next_time
    return intervals

def process_logs(folder_path, time_intervals):
    pattern = re.compile(r'\[(\d{2}:\d{2}:\d{2}\.\d{3})\]')
    stats = {f"{s.strftime('%Y-%m-%d %H:%M:%S')} - {e.strftime('%H:%M:%S')}": 0 
             for s, e in time_intervals}
    
    try:
        with open(folder_path, 'r', encoding='GB2312', errors='replace') as f:
            last_valid_time = None
            for line in f:
                # 时间戳处理
                time_match = pattern.search(line)
                current_time = None
                if time_match:
                    try:
                        t = datetime.strptime(time_match.group(1), "%H:%M:%S.%f")
                        t = t.replace(
                            year=time_intervals[0][0].year,
                            month=time_intervals[0][0].month,
                            day=time_intervals[0][0].day
                        )
                        current_time = t
                        last_valid_time = t
                    except:
                        pass
                
                # 特征统计逻辑
                if any(marker in line for marker in ['[p', 'p]']) or line.strip().endswith('p'):
                    effective_time = current_time or last_valid_time
                    if not effective_time:
                        continue
                    
                    # 二分查找优化区间定位
                    left, right = 0, len(time_intervals)-1
                    while left <= right:
                        mid = (left + right) // 2
                        s, e = time_intervals[mid]
                        if s <= effective_time < e:
                            time_key = f"{s.strftime('%Y-%m-%d %H:%M:%S')} - {e.strftime('%H:%M:%S')}"
                            stats[time_key] += 1
                            break
                        elif effective_time < s:
                            right = mid - 1
                        else:
                            left = mid + 1
    except Exception as e:
        print(f"处理文件 {folder_path} 时出错: {e}")
    
    return stats

def main():
    # 时间参数设置
    start_time = datetime(2025, 2, 27, 8, 14, 16)
    end_time = datetime(2025, 2, 27, 9, 00, 31)
    interval_minutes = 2
    
    # 路径选择
    log_dir = select_input_file_path()
    if not log_dir:
        print("未选择输入目录")
        return
    output_path = select_output_file_path()
    if not output_path:
        print("未选择输出路径")
        return
    
    # 生成时间区间
    time_intervals = generate_time_intervals(start_time, end_time, interval_minutes)
    
    # 处理日志
    result = process_logs(log_dir, time_intervals)
    print(result)
    
    # 保存结果
    df = pd.DataFrame({
        "时间区间": result.keys(),
        "出现次数": result.values()
    })
    df.to_excel(output_path, index=False)
    print(f"结果已保存至：{output_path}")

if __name__ == "__main__":
    main()